/**
 * @class refrigeratory.pn_users
 * @extends Ext.Panel
 *
 * refrigeratory.pn_users description
 *
 * @author    Maple
 * @copyright (c) 2009, refrigeratory
 * @date      23. February 2011
 * @version   0.1
 * @revision  0.1
 *
 */
 
// create namespace
Ext.ns('refrigeratory');

/**
 * Creates new refrigeratory.pn_users
 * @constructor
 * @param {Object} config A config object
 */
refrigeratory.pn_users = Ext.extend(Ext.Panel, {
	
    url: refrigeratory.REQUEST_URL

    ,initComponent:function() {
 
        // hard coded config (it cannot be changed while instantiating)
        // {{{
        var config = {        	
        	title: this.titleText
        	,id : 'pn_users'
			,closable: true
    		,autoScroll: true
    		,style:"height:100%;"
    		,bodyStyle:"height:100%;"
        }; // eo config object
 
        // apply config
        Ext.apply(this, Ext.apply(this.initialConfig, config));
        // }}}
 
        // call parent
        refrigeratory.pn_users.superclass.initComponent.apply(this, arguments);
 
        // parent call post-processing, e.g. install event handlers
 
    } // eo function initComponent

    ,onRender:function() {
     
        // parent call pre-processing
 
        // call parent
        refrigeratory.pn_users.superclass.onRender.apply(this, arguments);
 
        // parent call post-processing, e.g. install event handlers on rendered components
        this.add(this.createGp());
        this.doLayout();
 
    } // eo function onRender
    
    // 需本地化的文本
    ,titleText: '用户管理'
    ,addText: "增加"
    ,deleteText: "删除"
    ,saveText: '保存'

    // icon css class
    ,iconDelete: 'refrigeratory-icon-delete'
    ,iconAdd: 'refrigeratory-icon-add'
    ,iconSave: 'refrigeratory-icon-save'
    
    // private
    ,createGp: function(){
    	this.createRowActions();
    	this.createJstGroup();
    	var store = new Ext.data.JsonStore({
    		url: this.url
    		,baseParams: {
    			action:'user',
    			operation: 'get_users'
    		}
    		,root: 'data'
    		,fields:['uid', 'username', 'gid', 'lids','pwd'
					,{name: 'icon', mapping: 'icon', defaultValue: this.iconDelete}
					,{name: 'qtip', mapping: 'qtip', defaultValue: this.deleteText}
    		]
    		,autoLoad: false
    	});
    	store.on('load', this.onJstGpLoad, this);
    	store.on('beforeload', this.onJstGpBeforeLoad, this);
    	var renderGroup = function(value,metadata,record){  
    		var index = this.jstGroup.find("gid", value);
    		if (index!=-1)
    			return this.jstGroup.getAt(index).data["name"];
    		else
    			return value;
    	};
    	var renderLists = function(value,metadata,record){
    		if (!value) return value;
    		
    		var lids = value.split(",");
    		var members = "";
    		for(var i=0; i<lids.length; i++){
	    		var index = this.jstList.find("lid", lids[i]);
	    		if (index!=-1)
	    			lids[i] = this.jstList.getAt(index).data["lname"];
    		}
    		return lids.join(", ");
    	};
    	var cm = new Ext.grid.ColumnModel([
    		new Ext.grid.RowNumberer(),
    		{header: "用户名",		dataIndex:'username',  sortable: true, width:160, editor: new Ext.form.TextField({ allowBlank: false })}
			,{header: "密码",		dataIndex:'pwd', width:160, editor: new Ext.form.TextField({ allowBlank: false  })}
    		,{header: "用户组",		dataIndex:'gid',  sortable: true, width:160, editor: this.createCbbGroup(), renderer: renderGroup.createDelegate(this)}
    		,{header: "管理列表",	dataIndex:'lids', width:160, editor: this.createLcbLists(), renderer:renderLists.createDelegate(this)}
    		,this.rowActions
    	]);
    	var o = this.gp = new Ext.grid.EditorGridPanel({
    		title: this.titleText
    		,ds: store
    		,cm: cm
    		,tbar: this.createGpTbar()
    		,plugins: [this.rowActions]
    		,autoHeight: true
    		,border: false
    		,viewConfig: {
    			forceFit: false
    		}
    		,clicksToEdit: 1
    	});
    	o.on('afteredit', this.onGpAfterEdit, this);
    	return o;
    }
    
    // private
    ,createJstGroup: function(){
    	var o = this.jstGroup = new Ext.data.JsonStore({
		    url: this.url,
		    baseParams:{
    			action:'user',
    			operation: 'get_groups'
			},
		    fields: ['gid', 'name'],
		    root: 'data',
		    autoLoad: true
		});
		o.on('load', this.onJstGroupLoad, this);
    }
    
    // private  
    ,createCbbGroup: function(grades){
    	return new Ext.grid.GridEditor(new Ext.form.ComboBox({
			lazyRender:true,
			displayField: 'name',
			valueField: 'gid',
			triggerAction: 'all',
			anchor:'95%',
			width: 160,
			mode: 'local',
			editable: false,
			forceSelection: true,
			store: this.jstGroup
        }));
    }
    
    // private  
    ,createLcbLists: function(grades){
    	this.jstList = new Ext.data.JsonStore({
		    url: this.url,
		    baseParams:{
    			action:'list',
    			operation: 'get'
			},
		    fields: ['lid', 'lname'],
		    root: 'data',
		    autoLoad: true
		});
    	return new Ext.grid.GridEditor(new Ext.ux.form.LovCombo({
	        width:160
	        ,hideOnSelect:false
	        ,maxHeight:200
			,displayField: 'lname',
			valueField: 'lid',
			triggerAction: 'all',
			anchor:'95%',
			lazyInit: false,
			mode: 'local',
			editable: false,
			forceSelection: true,
			store: this.jstList
        }));
    }
    
    // private 生成rowActions
    ,createRowActions: function(){
        var o  = this. rowActions = new Ext.ux.grid.RowActions({
            header: "操作"
            ,width: 80
            ,autoWidth: false
            ,actions:[{
                iconIndex: 'icon'
                ,qtipIndex: 'qtip'
            }]
        });
        o.on('action', this.onRowActionsClick, this);
        return this.rowActions;
    }
    
    // private
    ,createGpTbar: function(){
    	var tb = [];
    	this.btnRefresh = new Ext.Toolbar.Button({
    		text: "刷新"
    		,handler: this.onBtnRefreshClick.createDelegate(this)
    	});
    	tb.push(this.btnRefresh);
    	return tb;
    }
    
    // private
    ,onJstGpBeforeLoad: function(){
    	this.getEl().mask("数据载入中...");
    }
    
    // private
    ,onJstGpLoad: function(store, records, options){
    	this.addRecord(store);
    	this.getEl().unmask();
    }
    // private
    ,onGpAfterEdit: function(e){
    	if (!e.record.data['newRecord']){
	    	e.record.set("icon", this.iconSave);
	    	e.record.set("qtip", this.saveText);
    	}
    }
    
    // private
	,addRecord:function(store) {
		if(store.recordType) {
			var rec = new store.recordType({newRecord:true});
			rec.data['icon'] = this.iconAdd;
			rec.data['qtip'] = this.addText;
			rec.commit();
			store.add(rec);
			return rec;
		}
		return false;
	} // eo function addRecord
	
	// private
    ,onRowActionsClick: function(grid, record, action, row, col){
    	
    	if (action == this.iconDelete){
	        Ext.MessageBox.confirm("确认", String.format("确认删除用户 {0} 吗？", record.data['username']), function(btn){
	                if (btn == "yes"){
	                    var uid = this.gp.store.getAt(row).get('uid');
	                    this.requestDelete(uid);
	                }
	            }, this
	        );
        }
        else if(action == this.iconAdd){
        	var rec = this.gp.store.getAt(row);
        	if (!rec.get('username') || !rec.get('gid')){
        		Ext.MessageBox.alert("提示", "请输入用户名并选择用户组！");
        	}
        	else{
        		this.requestAdd(rec.data);
        	}
        }
        else if (action == this.iconSave){
        	var rec = this.gp.store.getAt(row);
        	this.requestUpdate(rec.data);
        }
    }
    
    // private
    ,onBtnRefreshClick: function(){
    	this.reloadGp();
    }
    
    // private
    ,onJstGroupLoad: function(store, records, options){
    	this.gp.getStore().load();
    }
    
    // private
	,requestUpdate: function(data){
		this.getEl().mask("正在保存...");
    	Ext.Ajax.request({
    		url: this.url
    		,params:{
    			action:'user'
    			,operation: 'update'
    			,uid: data['uid']
    			,username: data['username']
    			,gid: data['gid']
    			,lids: data['lids']
				,pwd : data['pwd']
    		}
    		,success: this.requestUpdateSuccess
    		,scope: this
    	});
	}
    
    // private
    ,requestUpdateSuccess: function(response){
    	this.getEl().unmask();
    	var r = Ext.decode(response.responseText);
        if (r.success == true){
        	this.reloadGp();
        }
        else{
        	Ext.MessageBox.alert("提示", r.info);
        }
    }
    
    // private
	,requestDelete: function(uid){
		this.getEl().mask("正在保存...");
    	Ext.Ajax.request({
    		url: this.url
    		,params:{
    			action:'user'
    			,operation: 'delete'
    			,uid: uid
    		}
    		,success: this.requestDeleteSuccess
    		,scope: this
    	});
	}
    
    // private
    ,requestDeleteSuccess: function(response){
    	this.getEl().unmask();
    	var r = Ext.decode(response.responseText);
        if (r.success == true){
        	this.reloadGp();
        }
        else{
        	Ext.MessageBox.alert("提示", r.info);
        }
    }
    
    // private
	,requestAdd: function(data){
		this.getEl().mask("正在保存...");
    	Ext.Ajax.request({
    		url: this.url
    		,params:{
    			action:'user'
    			,operation: 'add'
    			,gid: data['gid']
    			,username: data['username']
    			,lids: data['lids']
				,pwd : data['pwd']
    		}
    		,success: this.requestAddSuccess
    		,scope: this
    	});
	}
    
    // private
    ,requestAddSuccess: function(response){
    	this.getEl().unmask();
    	var r = Ext.decode(response.responseText);
        if (r.success == true){
        	//this.gp.store.commitChanges();
        	this.reloadGp();
        }
        else{
        	Ext.MessageBox.alert("提示", r.info);
        }
    }
    
    // private
    ,reloadGp: function(){
        this.gp.store.reload({
        	params:{
    			action:'user',
    			operation: 'get_users'
        	}
        });
    }
}); // eo extend
 
// register xtype
Ext.reg('pn_users', refrigeratory.pn_users); 
// eof